<template>
    <a class="file-card" :href="fileInfo.fileURL" target="_blank" rel="noopener">
        <!-- 图片直接预览 -->
        <!-- props.fileInfo.isImage         避免文件信息没有image这个属性，所以手写一个函数来判断 -->
        <img v-if="isImage(props.fileInfo.fileName)" :src="props.fileInfo.fileURL ?? props.fileInfo.fileUrl"
            :alt="props.fileInfo.fileName" class="thumb" />
        <!-- 非图片显示图标 + 文件名 + 大小 -->
        <div v-else class="file-info">
            <img :src="getIcon(fileInfo.fileName)" class="icon" />
            <span class="name">{{ fileInfo.fileName }}</span>
            <span class="size">{{ prettySize(fileInfo.fileSize) }}</span>
        </div>
    </a>
</template>

<script setup lang="ts">
const props = defineProps<{ fileInfo: any }>()


import PdfImage from "@images/General/file/pdf.svg"
import TextImage from "@images/General/file/txt.svg"

const prettySize = (bytes: number) => {
    if (bytes < 1024) return bytes + ' B'
    const k = 1024
    const sizes = ['KB', 'MB', 'GB']
    let i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i - 1]
}

const getIcon = (name: string) => {
    const ext = name.split('.').pop()?.toLowerCase()
    if (ext === 'pdf') return PdfImage
    if (ext === 'txt') return TextImage
    return '/icons/file.svg'
}

// 判断嫩见是否为图片
function isImage(fileName: string) {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
    return imageExtensions.some((ext: string) => fileName.toLowerCase().endsWith(ext));
}

</script>

<style scoped>
.file-card {
    display: inline-block;
    max-width: 220px;
    border: 1px solid #e5e5e5;
    border-radius: 6px;
    overflow: hidden;
    text-decoration: none;
    color: inherit;
}

.thumb {
    width: 100px;
    /* width: 100%; */
    height: auto;
    display: block;
}

.file-info {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 6px 8px;
    background: #fafafa;
    font-size: 12px;
}

.icon {
    width: 20px;
    height: 20px;
}

.name {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.size {
    color: #999;
}
</style>